<script setup>
const props = defineProps({
  modelValue: [Boolean, String, Number],
  activeValue: {
    type: [Boolean, String, Number],
    default: 1,
  },
  inactiveValue: {
    type: [Boolean, String, Number],
    default: 0,
  },
  activeText: {
    type: String,
    default: "是",
  },
  inactiveText: {
    type: String,
    default: "否",
  },
  loading: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: "确认修改吗？",
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  beforeChange: Function,
});

const emits = defineEmits(["update:modelValue", "change"]);

const loading = ref(props.loading);

const handleBeforeChange = () => {
  loading.value = true;
  return new Promise(async (resolve) => {
    if (props.beforeChange) {
      await props.beforeChange();
    } else resolve(true);
    loading.value = false;
  });
};

const onChange = (val) => {
  emits("update:modelValue", val);
  emits("change", val);
};

const confirm = async () => {
  loading.value = true;
  try {
    await props.beforeChange();
    loading.value = false;
  } catch (e) {
    loading.value = false;
  }
};
</script>
<template>
  <el-popconfirm :title="title" :disabled="disabled" @confirm="confirm">
    <template #reference>
      <div class="switch">
        <el-switch
          :model-value="modelValue"
          inline-prompt
          :active-value="activeValue"
          :inactive-value="inactiveValue"
          :active-text="activeText"
          :inactive-text="inactiveText"
          :disabled="disabled"
          :loading="loading"
          v-bind="$attrs"
        ></el-switch>
        <div
          class="cover"
          :style="{ cursor: disabled === true ? 'no-drop' : 'pointer' }"
        ></div>
      </div>
    </template>
  </el-popconfirm>
</template>
<script>
export default {
  name: "Switch",
};
</script>
<style scoped lang="scss">
.switch {
  position: relative;
  .cover {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    cursor: pointer;
  }
}
</style>
